package com.buss.util.http;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import java.io.UnsupportedEncodingException;
import java.net.ConnectException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class HttpUtil {
	private static final Logger LOG = Logger.getLogger(HttpUtil.class);
	public static void sendPost(String httpServiceURL, Map<String, Object> params, String reqCharSet, String respCharSet,final HttpCallBackListener listener) {
		long startTime = System.currentTimeMillis();
		long endTime = startTime;
		String result = "";
		String errroMsg = "";
		
		try {
			
			HttpPost httpPost = new HttpPost(httpServiceURL);
			List<NameValuePair> nvps = new ArrayList <NameValuePair>();

			for(Entry<String, Object> entry : params.entrySet()){
				nvps.add(new BasicNameValuePair(entry.getKey(),entry.getValue().toString()));
			}
			
			httpPost.setEntity(new UrlEncodedFormEntity(nvps, reqCharSet));
			HttpResponse response = HttpClientUtil.getHttpClient().execute(httpPost);
			HttpEntity entity = response.getEntity();
			result = EntityUtils.toString(response.getEntity(), respCharSet);
			EntityUtils.consume(entity);
			LOG.info("目标系统返回数据{}"+result);
			try{
				JSONObject jsonObject= JSONObject.parseObject(result);
				if(listener!=null){
					//回调onFinish方法
					listener.onFinish(result);
				}
			}catch(Exception e){
				errroMsg="解析目标系统返回数据错误";
				if(listener!=null){
					listener.onError(errroMsg, e);
				}
			}
			
			endTime = System.currentTimeMillis();
			
		}catch (HttpHostConnectException e) {
			errroMsg = "目标系统拒绝访问，请联系相关技术人员!";
			if(listener!=null){
				listener.onError(errroMsg,e);
			}
			LOG.error(errroMsg, e);
		} catch (ConnectException e) {
			errroMsg = "连接目标系统超时，请联系相关技术人员!";
			if(listener!=null){
				listener.onError(errroMsg,e);
			}
			LOG.error(errroMsg, e);
		} catch (UnsupportedEncodingException e) {
			errroMsg = "编码异常!";
			if(listener!=null){
				listener.onError(errroMsg,e);
			}
			LOG.error(errroMsg, e);
		}catch (Exception e) {
			errroMsg = "调用目标系统时出现异常!";
			if(listener!=null){
				listener.onError(errroMsg,e);
			}
			LOG.error(errroMsg, e);
		}finally {
			LOG.info("接口执行耗时(毫秒)： " + (endTime - startTime));
		}
		
	}
}
